//
// Created by XUAN on 2024/8/27.
//

#include "sysGetConfig.h"

#include <audio_tone_uri.h>
#include <audio_wrapper.h>
#include <circuit_board.h>
#include <cJSON.h>
#include <esp_heap_caps.h>
#include <esp_http_client.h>
#include <esp_log.h>
#include <my_led_strip.h>


/*--------------------------parameters-----------------------*/
static const char *TAG = "SYS_CONFIG";

char mqtt_server[60] = {0};
int mqtt_port = 1888;
char *base_url;
char *SERVER_CHAT_URL;
char *msg_data;
char *post_msg_data;

bool sys_Config_get = false;
/*--------------------------parameters-----------------------*/

/*--------------------------main-----------------------*/
extern char BT_MAC[35];
/*--------------------------main-----------------------*/


/*+++++++++++++++++++++++++++++++LED+++++++++++++++++++++++++++++++*/
extern int RUNNING_LED_NUMBER;
extern int R_COLOR;
extern int G_COLOR;
extern int B_COLOR;
extern int BREATH_R_COLOR;
extern int BREATH_G_COLOR;
extern int BREATH_B_COLOR;
extern int RUNNING_R_COLOR;
extern int RUNNING_G_COLOR;
extern int RUNNING_B_COLOR;
extern int RUNNING_DELAY;
extern int BREATHING_DELAY;
/*--------------------------LED-----------------------*/


void get_sysConfig_init() {
    base_url = (char *)heap_caps_malloc(300, MALLOC_CAP_SPIRAM);
    post_msg_data = (char *)heap_caps_malloc(300, MALLOC_CAP_SPIRAM);
    msg_data = (char *)heap_caps_malloc(2000, MALLOC_CAP_SPIRAM);
    SERVER_CHAT_URL = (char *)heap_caps_malloc(200 * sizeof(uint8_t), MALLOC_CAP_SPIRAM);

    assert(msg_data != NULL);
}


int msg_index = 0;

int dd = 0;
esp_err_t msg_http_event_handler(esp_http_client_event_t *evt)
{
    static char *output_buffer; // Buffer to store response of http request from event handler
    static int output_len;      // Stores number of bytes read
    switch (evt->event_id)
    {
    case HTTP_EVENT_ERROR:
        ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
        break;
    case HTTP_EVENT_ON_CONNECTED:

        memset(msg_data, 0, msg_index + 1);
        msg_index = 0;
        ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
        break;
    case HTTP_EVENT_HEADER_SENT:
        ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
        break;
    case HTTP_EVENT_ON_HEADER:
        break;
    case HTTP_EVENT_ON_DATA:
    {
        for (dd = msg_index; dd < msg_index + evt->data_len; dd++)
        {
            // printf("%c", ((char *)evt->data)[i - msg_index]);
            msg_data[dd] = ((char *)evt->data)[dd - msg_index];
        }
        msg_index = msg_index + evt->data_len;
    }
    break;
    case HTTP_EVENT_ON_FINISH:
        // ESP_LOGI(TAG, "HTTP_EVENT_ON_FINISH");
        if (output_buffer != NULL)
        {
            free(output_buffer);
            output_buffer = NULL;
        }
        output_len = 0;
        break;
    case HTTP_EVENT_DISCONNECTED:
    {
        ESP_LOGI(TAG, "请求配置文件数据:%.*s", msg_index, msg_data);
        cJSON *root = NULL;
        root = cJSON_Parse(msg_data);
        if (!root)
        {
            printf("Error before: [%s]\n", cJSON_GetErrorPtr());
            break;
        }
        else
        {

            if (strcmp(cJSON_GetObjectItem(root, "message")->valuestring, "success") == 0)
            {
                cJSON *data = cJSON_GetObjectItem(root, "data");
                cJSON *data_obj = cJSON_Parse(data->valuestring);

                if (cJSON_GetObjectItem(data_obj, "base_url") != NULL)
                {
                    sprintf(base_url, "%s", cJSON_GetObjectItem(data_obj, "base_url")->valuestring);
                    base_url = strchr(base_url, ':') + 3;
                    sprintf(SERVER_CHAT_URL, "http://%s/chat/",base_url);
                }
                if (cJSON_GetObjectItem(data_obj, "mqtt_server") != NULL)
                    sprintf(mqtt_server, "%s", cJSON_GetObjectItem(data_obj, "mqtt_server")->valuestring);
                if (cJSON_GetObjectItem(data_obj, "mqtt_port") != NULL)
                    mqtt_port = cJSON_GetObjectItem(data_obj, "mqtt_port")->valueint;
                if (cJSON_GetObjectItem(data_obj, "welcome_wav") != NULL) {
                    if(strcmp(cJSON_GetObjectItem(data_obj, "welcome_wav")->valuestring,"") != 0) {
                        chat_audio_player_play(cJSON_GetObjectItem(data_obj, "welcome_wav")->valuestring);
                    }
                }
                if (cJSON_GetObjectItem(data_obj, "RUNNING_LED_NUMBER") != NULL)
                    RUNNING_LED_NUMBER = cJSON_GetObjectItem(data_obj, "RUNNING_LED_NUMBER")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "R_COLOR") != NULL)
                    R_COLOR = cJSON_GetObjectItem(data_obj, "R_COLOR")->valueint; // Range [0:0xff]  hex
                if (cJSON_GetObjectItem(data_obj, "G_COLOR") != NULL)
                {
                    G_COLOR = cJSON_GetObjectItem(data_obj, "G_COLOR")->valueint; // Range [0:0xff]  hex
                    ESP_LOGE(TAG, "G_COLOR:%d", G_COLOR);
                }
                if (cJSON_GetObjectItem(data_obj, "B_COLOR") != NULL)
                    B_COLOR = cJSON_GetObjectItem(data_obj, "B_COLOR")->valueint; // Range [0:0xff]  hex
                if (cJSON_GetObjectItem(data_obj, "BREATH_R_COLOR") != NULL)
                    BREATH_R_COLOR = cJSON_GetObjectItem(data_obj, "BREATH_R_COLOR")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "BREATH_G_COLOR") != NULL)
                {
                    BREATH_G_COLOR = cJSON_GetObjectItem(data_obj, "BREATH_G_COLOR")->valueint; //
                }
                if (cJSON_GetObjectItem(data_obj, "BREATH_B_COLOR ") != NULL)
                    BREATH_B_COLOR = cJSON_GetObjectItem(data_obj, "BREATH_B_COLOR")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "RUNNING_R_COLOR") != NULL)
                    RUNNING_R_COLOR = cJSON_GetObjectItem(data_obj, "RUNNING_R_COLOR")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "RUNNING_G_COLOR") != NULL)
                    RUNNING_G_COLOR = cJSON_GetObjectItem(data_obj, "RUNNING_G_COLOR")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "RUNNING_B_COLOR") != NULL)
                    RUNNING_B_COLOR = cJSON_GetObjectItem(data_obj, "RUNNING_B_COLOR")->valueint; //
                if (cJSON_GetObjectItem(data_obj, "RUNNING_DELAY") != NULL)
                {
                    RUNNING_DELAY = cJSON_GetObjectItem(data_obj, "RUNNING_DELAY")->valueint; //  running interval 200ms the bigger the slower
                    // ESP_LOGE(TAG, "RUNNING_DELAY:%d", RUNNING_DELAY);
                }
                if (cJSON_GetObjectItem(data_obj, "BREATHING_DELAY") != NULL)
                    BREATHING_DELAY = cJSON_GetObjectItem(data_obj, "BREATHING_DELAY")->valueint; // 50ms the bigger the slower

                ESP_LOGI(TAG, "GET_BASE_URL:%s-- MQTT_SERVER:%s  %d", base_url, mqtt_server, mqtt_port);
                cJSON_Delete(data_obj);
            }
        }
        cJSON_Delete(root);
    }
    break;
    case HTTP_EVENT_REDIRECT:
        ESP_LOGD(TAG, "HTTP_EVENT_REDIRECT");
        esp_http_client_set_header(evt->client, "From", "user@example.com");
        esp_http_client_set_header(evt->client, "Accept", "text/html");
        esp_http_client_set_redirection(evt->client);
        break;
    }
    return ESP_OK;
}

int msg_cnt = 0;
void get_sysConfig_On_Starting()
{
    while (1)
    {
        msg_cnt++;
        ESP_LOGI(TAG, "开机第一次准备请求文件");
        if (base_url[0] == 0)
        {
            ESP_LOGI(TAG, "还未请求到");
        }
        if (msg_cnt == 7)
        {
            ESP_LOGI(TAG, "多次未请求到，播放网络异常");
            play_tone(NET_WRONG);
        }
        if (base_url[0] != 0 && mqtt_server[0] != 0)
            break;
        esp_http_client_config_t config = {
            .url = "/dev/",  //请求配置文件服务地址
            .timeout_ms = 10000,
            .event_handler = msg_http_event_handler,
        };
        esp_http_client_handle_t get_msg_client = esp_http_client_init(&config);
        esp_err_t err;
        esp_http_client_set_method(get_msg_client, HTTP_METHOD_POST);
        sprintf(post_msg_data, "{\"devId\":\"%s\",\"version\":\"%s\"}", BT_MAC,  "AiSpea_MDDD");
        esp_http_client_set_post_field(get_msg_client, (char *)post_msg_data, strlen(post_msg_data));

        err = esp_http_client_perform(get_msg_client);
        if (err == ESP_OK)
        {
            ESP_LOGI(TAG, "HTTP GET Status = %d, content_length =%" PRId64, esp_http_client_get_status_code(get_msg_client), esp_http_client_get_content_length(get_msg_client));
        }
        else
        {
            ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err));
            // 在第一次失败时重新连接网络，并等待连接成功
        }
        esp_http_client_cleanup(get_msg_client);
        vTaskDelay(1000);
    }
}


